package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/*
    菜单接口实现类
 */
@Service(interfaceClass = MenuService.class)
@Transactional //事务注解
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;


    /*
        分页查询所有菜单
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Menu> list = menuDao.findPage(queryString);
        return new PageResult(list.getTotal(),list.getResult());
    }

    // 查询所有一级菜单
    @Override
    public List<Map<String, Object>> findFirstMenu() {
        return menuDao.findFirstMenu();
    }

    //添加菜单
    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    //删除菜单
    @Override
    public void deleteById(Integer id) {
        // 查询该id下有没有子菜单
        int count = menuDao.findCountByPanentMenuId(id);

        if (count > 0){
            throw new RuntimeException(MessageConstant.ERROR_MENU_CHILDMENU);
        }
        //菜单有没有关联角色
        int count2 = menuDao.findRoleCountByMenuId(id);
        if (count2 > 0){
            throw new RuntimeException(MessageConstant.ERROR_MENU_ROLE);
        }
        //没有子菜单 删除
        menuDao.deleteById(id);
    }

    // 根据id查询菜单信息 回显
    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    /*
        编辑菜单
     */
    @Override
    public void edit(Menu menu) {
        Integer parentMenuId = menu.getParentMenuId();
        Integer id = menu.getId();
        if (parentMenuId==id){
            throw new RuntimeException(MessageConstant.ERROR_SELFTOSELF);
        }
        menuDao.edit(menu);
    }
    @Override
    public List<Map<String, Object>> findMenuAll() {
        return menuDao.findMenuAll();
    }


}
